/*
 * @Author: zhangfeng
 * @Date: 2023-12-28 17:09:30
 * @LastEditTime: 2023-12-29 15:47:37
 * @LastEditors: zhangfeng
 * @Description:
 * @FilePath: \nodeapi\src\controller\role-premisssion.controller.js
 * © 2023 张峰，All rights reserved.
 */
const {
  createServer,
  deleteRolePremissionServer,
  getRolePremissionServer,
} = require("../server/role-premission.server");

const {
  rolePremissionCreateFormatterError,
  rolePremissionGetFormatterError,
  rolePremissionGetFormatterEmpty,
} = require("../constants/err.type");

class RolePremissionController {
  async create(ctx, next) {
    const { premissionId, roleId } = ctx.request.body;
    const rolePremissionArray = [];
    if (Array.isArray(premissionId) && Array.isArray(roleId)) {
      roleId.map((role) => {
        premissionId.map((premission) => {
          rolePremissionArray.push({
            roleId: role,
            premissionId: premission,
          });
        });
      });
    } else if (!Array.isArray(premissionId) && Array.isArray(roleId)) {
      roleId.map((role) => {
        rolePremissionArray.push({
          roleId: role,
          premissionId: premissionId,
        });
      });
    } else if (Array.isArray(premissionId) && !Array.isArray(roleId)) {
      premissionId.map((premission) => {
        rolePremissionArray.push({
          roleId: roleId,
          premissionId: premission,
        });
      });
    } else {
      rolePremissionArray.push({
        roleId: roleId,
        premissionId: premissionId,
      });
    }
    try {
      const res = await deleteRolePremissionServer(roleId);
      const result = await createServer(rolePremissionArray);
      if (result) {
        ctx.body = {
          code: 0,
          message: "角色权限绑定成功",
          result: "",
        };
      } else {
        ctx.body = rolePremissionCreateFormatterError;
      }
    } catch (error) {
      console.error(error);
      ctx.body = rolePremissionCreateFormatterError;
    }
  }

  async getPremission(ctx, next) {
    const { roleId } = ctx.request.query;

    try {
      const result = await getRolePremissionServer(roleId);
      ctx.body = {
        code: 0,
        message: "获取角色权限成功",
        result: {
          premissionId:
            result.length > 0 ? result.map((v) => v.premissionId) : result,
        },
      };
    } catch (error) {
      console.error(error);
      ctx.body = rolePremissionGetFormatterError;
    }
  }
}

module.exports = new RolePremissionController();
